<template>
  <div>
    <input type="file" @change="handleFile1Change" ref="fileInput1" accept=".pdf" />
    <input type="file" @change="handleFile2Change" ref="fileInput2" accept=".pdf" />
    <button @click="comparePDFs">比较 PDF</button>
    <code-diff
      v-if="oldText && newText"
      :old-string="oldText"
      :new-string="newText"
      file-name="test.txt"
      diffStyle="char"
      output-format="side-by-side"
    />
  </div>
</template>

<script>
import { CodeDiff } from 'v-code-diff'
import pdfjsLib from 'pdfjs-dist' // 引入 pdf.js

export default {
  name: 'App',
  components: {
    CodeDiff
  },
  data () {
    return {
      file1: null,
      file2: null,
      oldText: '',
      newText: ''
    }
  },
  methods: {
    handleFile1Change (event) {
      this.file1 = event.target.files[0]
    },
    handleFile2Change (event) {
      this.file2 = event.target.files[0]
    },
    async extractTextFromPDF (file) {
      const loadingTask = pdfjsLib.getDocument(URL.createObjectURL(file))
      const pdf = await loadingTask.promise
      let textContent = ''
      for (let i = 1; i <= pdf.numPages; i++) {
        const page = await pdf.getPage(i)
        const textContentObj = await page.getTextContent()
        // 处理每一页的文本，尝试保留换行信息
        let pageText = ''
        let lastY = null
        for (const item of textContentObj.items) {
          if (lastY !== null && item.transform[5] !== lastY) {
            // 如果 Y 坐标不同，认为是新的一行，添加换行符
            pageText += '\n'
          }
          pageText += item.str
          lastY = item.transform[5]
        }
        textContent += pageText + '\n' // 每一页结束后添加换行符
      }
      return textContent
    },
    async comparePDFs () {
      if (!this.file1 || !this.file2) {
        alert('请选择两个 PDF 文件。')
        return
      }
      this.oldText = await this.extractTextFromPDF(this.file1)
      this.newText = await this.extractTextFromPDF(this.file2)
    }
  }
}
</script>
